package com.leyou.sms.mq;

import com.leyou.common.utils.RegexUtils;
import com.leyou.sms.utils.SmsHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Map;

import static com.leyou.common.constants.MQConstants.ExchangeConstants.SMS_EXCHANGE_NAME;
import static com.leyou.common.constants.MQConstants.QueueConstants.SMS_VERIFY_CODE_QUEUE;
import static com.leyou.common.constants.MQConstants.RoutingKeyConstants.VERIFY_CODE_KEY;

/**
 * @author 虎哥
 */
@Slf4j
@Component
public class MessageListener {

    private final SmsHelper smsHelper;

    public MessageListener(SmsHelper smsHelper) {
        this.smsHelper = smsHelper;
    }

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = SMS_VERIFY_CODE_QUEUE, durable = "true"),
            exchange = @Exchange(name = SMS_EXCHANGE_NAME, type = ExchangeTypes.TOPIC),
            key = VERIFY_CODE_KEY
    ))
    public void listenVerifyCodeMessage(Map<String,String> map){
        if (CollectionUtils.isEmpty(map)) {
            // 消息为空，丢弃
            return;
        }
        // 校验手机号码
        String phone = map.get("phone");
        if (!RegexUtils.isPhone(phone)) {
            // 手机号有误，丢弃
            return;
        }
        // 校验code
        String code = map.get("code");
        if (!RegexUtils.isCodeValid(code)) {
            // code有误，丢弃
            return;
        }
        // 发送短信
        try {
            smsHelper.sendVerifyCode(phone, code);
        } catch (Exception e) {
            log.error("发送短信失败", e);
        }
    }
}
